import Store from '../store'
import { chatatABC } from '../utils/util'
import Dialog from '../utils/dialog'
// import { getRangetxt } from '../methods/get'
import { luckysheetrefreshgrid, jfrefreshgrid } from './refresh'
import { luckysheetextendtable, luckysheetdeletetable, luckysheetDeleteCell } from './extend'

function getRange() {
  const select = Store.luckysheet_select_save[0]
  return {
    rangTxt: `=$${chatatABC(select.column[0])}$${select.row[0] + 1}:$${chatatABC(select.column[1])}$${select.row[1] +
      1}`,
    rangObj: { row: select.row, col: select.column }
  }
}

function generateFiveDigitRandomNumber() {
  return Math.floor(Math.random() * 90000) + 10000
}

window.isDuplCell = ({ cellVal, curCol, curRow, rangObj }) => {
  if (!rangObj) {
    return false
  }
  const { row: rangRow, col: rangCol } = rangObj

  const set = new Set()
  for (let c = rangCol[0]; c <= rangCol[1]; c++) {
    for (let r = rangRow[0]; r <= rangRow[1]; r++) {
      // Store.flowdata[r][c] && Store.flowdata[r][c].v != null &&
      if (Store.flowdata[r][c]?.v && !set.has(`${Store.flowdata[r][c]?.v}`) && (r != curRow || c != curCol)) {
        set.add(`${Store.flowdata[r][c]?.v}`)
      }
    }
  }

  return set.has(`${cellVal}`)
}

function doSomethingOnDuplicate({ data, rangObj, cb, duplId, isClear, isColor, isBuble }) {
  const { row: rangRow, col: rangCol } = rangObj
  // 一列一列处理
  // const map = new Map()
  for (let c = rangCol[0]; c <= rangCol[1]; c++) {
    for (let r = rangRow[0]; r <= rangRow[1]; r++) {
      if (data[r][c]) {
        // let val = data[r][c].v

        // cb(data[r][c]) //下面的if-else可以改为cb回调的形式，但是写在这里就不用换来换去了，哈哈哈
        if (isClear && isClear === 'color') {
          delete data[r][c]._dupl?.isColor
          delete Store.config?.duplConfig[data[r][c]._dupl?.id]?.isColor
          // isClear === 'color' ? delete data[r][c]._dupl?.isColor : delete data[r][c]._dupl?.isBuble
        } else if (isClear && isClear === 'buble') {
          delete data[r][c]._dupl?.isBuble
          delete Store.config?.duplConfig[data[r][c]._dupl?.id]?.isBuble
        } else {
          data[r][c]._dupl = { id: duplId, ...data[r][c]._dupl }
          isColor ? (data[r][c]._dupl.isColor = true) : ''
          isBuble ? (data[r][c]._dupl.isBuble = true) : ''
        }

        /* if (val == null) {
          continue
        }
        if (!map.has(`${val}`)) {
          //全部转为字符串
          map.set(`${val}`, data[r][c])
        } */
      } else {
        if (!isClear) {
          data[r][c] = { _dupl: { id: duplId } } //单元格的_dupl只用给id，在draw时用cell.v与前面的set作比较，
          //   这里给对象是保留可扩展性
          isColor ? (data[r][c]._dupl.isColor = true) : ''
          isBuble ? (data[r][c]._dupl.isBuble = true) : ''
        }
      }
    }
  }
  // 最后刷新，使其在界面显示
  jfrefreshgrid()
}

// 设置高亮重复项
function heighlightDuplItems() {
  let { rangTxt, rangObj } = getRange()
debugger
  const dialog = new Dialog({
    titleText: '高亮显示重复值',
    content: `
        <div>
            <div>以下区域如果存在重复单元格，这些单元格会被标记为橙色背景</div>
            <div>${rangTxt}</div>
        </div>
        `,
    confirm() {
      const duplId = generateFiveDigitRandomNumber()

      if (!Store.config.duplConfig) {
        Store.config.duplConfig = {}
      }
      // Store.config.duplConfig[duplId] = new Set()
      Store.config.duplConfig[duplId] = { ...Store.config.duplConfig[duplId], rangObj, isColor: true }

      doSomethingOnDuplicate({
        data: Store.flowdata,
        rangObj,
        isColor: true,
        // cb(curCell, preCell, val) {
        //   Store.config.duplConfig[duplId].add(`${val}`)
        // },
        duplId
      })
      dialog.hide()
    },
    cancel() {
      dialog.hide()
    }
  })
  debugger
  dialog.show()
}
// 清除高亮重复项
function clearHeighlightDuplItems() {
  let { rangObj } = getRange()
  doSomethingOnDuplicate({
    data: Store.flowdata,
    rangObj,
    isClear: 'color'
  })
}
// 设置 拒绝进入重复项
function refuseEnterDuplItems() {
  let { rangObj, rangTxt } = getRange()
  const duplId = generateFiveDigitRandomNumber()

  const dialog = new Dialog({
    titleText: '高亮显示重复值',
    content: `
            <div>
                <div>以下区域如果存在重复单元格，则提醒检查内容的准确性</div>
                <div>${rangTxt}</div>
            </div>
            `,
    confirm() {
      if (!Store.config.duplConfig) {
        Store.config.duplConfig = {}
      }
      // Store.config.duplConfig[duplId] = new Set()
      Store.config.duplConfig[duplId] = { ...Store.config.duplConfig[duplId], rangObj, isBuble: true }

      doSomethingOnDuplicate({
        data: Store.flowdata,
        rangObj,
        isBuble: true,
        duplId
        // cb(curCell, preCell, val) {
        //   Store.config.duplConfig[duplId].add(val)
        // }
      })
      dialog.hide()
    },
    cancel() {
      dialog.hide()
    }
  })
  dialog.show()

  //重复项检查 的弹框
  if (document.querySelector('#duplicateBuble') == null) {
    let bubleDom = `<div id='duplicateBuble' class='dupl_item' 
        style='position:absolute;left:-300px;top:-300px;z-index:9999;box-shadow:3px 2px 3px 1px #aca6a6;' >
            <div style='padding:4px 6px;background:white;white-space:nowrap;'>
                <div style="display: flex;align-items: center;justify-content: space-between;">
                    <div style="font-weight:800;">拒绝重复输入</div>
                    <div id="closeIconBtn" ><svg style="height:20px;width:20px;" t="1715764789805" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8041" width="200" height="200"><path d="M512 466.944l233.472-233.472a31.744 31.744 0 0 1 45.056 45.056L557.056 512l233.472 233.472a31.744 31.744 0 0 1-45.056 45.056L512 557.056l-233.472 233.472a31.744 31.744 0 0 1-45.056-45.056L466.944 512 233.472 278.528a31.744 31.744 0 0 1 45.056-45.056z" fill="#5A5A68" p-id="8042"></path></svg></div>
                </div>
                <div>
                    <div>当前输入的内容，与本区域的其他单元格内容重复。</div>
                    <div>再次[Enter]确认输入</div>
                </div>
            </div>
        </div>`
    setTimeout(() => {
      $('#duplicateBuble #closeIconBtn').on('click', function() {
        $('#duplicateBuble').css('left', '-300px')
      })
    })
    $('#luckysheet-cell-main').append(bubleDom)
  }
}
// 清除拒绝进入重复项
function clearRefuseEnterDuplItems() {
  let { rangObj } = getRange()
  doSomethingOnDuplicate({
    data: Store.flowdata,
    rangObj,
    isClear: 'buble'
  })
}

// 删除重复项
function deleteDupl() {
  let { rangObj, rangTxt } = getRange()
  const { dupl, unique } = deleteDuplData({ rangObj, getDuplResult: true })

  if (rangObj.col[0] === rangObj.col[1]) {
    // 只有一列，需要让用户判断是否扩展选区
    const dialog = new Dialog({
      titleText: '删除重复项',
      confirmText: '删除重复项',

      content: `
            <div>
                <div>是否扩展选区</div>
                <div >
                  <input type="radio" checked id="option1" name="choice" value="扩展选区">
                  <label for="option1">扩展选区</label><br>
                  <input type="radio" id="option2" name="choice" value="当前选定区域">
                  <label for="option2">当前选定区域</label><br>
                </div>
            </div>
            `,
      confirm() {
        if (document.querySelector('#option1')?.checked) {
          // 扩展选区，
          const d = Store.flowdata
          let last = Store.luckysheet_select_save[0]
          let r1 = last['row'][0],
            r2 = last['row'][1]
          let c1 = last['column'][0],
            c2 = last['column'][1]
          let rowS = r1
          let rowE = r2
          let colS = c1
          let colE = c2
          // 默认 扩展其他列 时 ， 用户就只选了一列，即colS 等于 colE
          // 左边
          for (let c = colS - 1; c >= 0; c--) {
            let isNotNull_count = 0
            for (let r = rowS; r <= rowE; r++) {
              if (d[r][c] && d[r][c]?.m != '' && d[r][c]?.m != null) {
                isNotNull_count++
              }
            }
            if (isNotNull_count === 0) {
              colS = c + 1
              break
            }
          }

          // 右边
          for (let c = colE + 1; c <= d[0].length; c++) {
            let isNotNull_count = 0
            for (let r = rowS; r <= rowE; r++) {
              if (d[r][c] && d[r][c]?.m != '' && d[r][c]?.m != null) {
                isNotNull_count++
              }
            }
            if (isNotNull_count === 0) {
              colE = c - 1
              break
            }
          }

          // luckysheet.setRangeShow({row:[rowS,rowE],column:[colS,colE]})
          deleteDuplData({ rangObj: { row: [rowS, rowE], col: [colS, colE] }, baseCol: rangObj.col[0] })
        } else {
          deleteDuplData({ rangObj })
        }

        dialog.hide()
      },
      cancel() {
        dialog.hide()
      }
    })
    dialog.show()
  } else {
    const dialog = new Dialog({
      titleText: '删除重复项',
      confirmText: '删除重复项',
      bottomBtnContent: `<div>
        <span>找到${dupl}条重复项；</span><br/>
        <span>删除后将保留${unique}条唯一项；</span>
      </div>`,
      content: `
              <div>
                  <div>以下区域如果存在重复单元格，则进行删除</div>
                  <div>${rangTxt}</div>
              </div>
              `,
      confirm() {
        deleteDuplData({ rangObj })
        dialog.hide()
      },
      cancel() {
        dialog.hide()
      }
    })
    dialog.show()
  }
}
// luckysheetDeleteCell('moveUp', str, edr, stc, edc);
function deleteDuplData({ rangObj, baseCol, getDuplResult = false }) {
  let result = { dupl: 0, unique: rangObj.row[1] - rangObj.row[0] }
  const curData = $.extend([], Store.flowdata)

  let duplSet = new Set()
  // for (let r = rangObj.row[0]; r <= rangObj.row[1]; r++) {
  for (let r = rangObj.row[1]; r >= rangObj.row[0]; r--) {
    let arr = []
    // for (let c = rangObj.col[0]; c <= rangObj.col[1]; c++) {
    for (let c = rangObj.col[1]; c >= rangObj.col[0]; c--) {
      if (curData[r][c]?.v != null) {
        arr.push(curData[r][c]?.v)
      }
    }
    if (baseCol != null) {
      // 是扩展选区，只用判断baseCol的列
      if (curData[r][baseCol]?.v != null && !duplSet.has(`${curData[r][baseCol]?.v}`)) {
        duplSet.add(`${curData[r][baseCol]?.v }`)
      } else if (duplSet.has(`${curData[r][baseCol]?.v}`)) {
        result.dupl++
        result.unique--
        if (getDuplResult === false) {
          luckysheetDeleteCell('moveUp', r, r, rangObj.col[0], rangObj.col[1])
        }
      }
    } else {
      if (arr.length > 0) {
        if (!duplSet.has(arr.join('**'))) {
          duplSet.add(arr.join('**'))
        } else if (duplSet.has(arr.join('**'))) {
          result.dupl++
          result.unique--
          if (getDuplResult === false) {
            luckysheetDeleteCell('moveUp', r, r, rangObj.col[0], rangObj.col[1])
          }
        }
      }
    }
  }
  return result
}

export { heighlightDuplItems, clearHeighlightDuplItems, refuseEnterDuplItems, clearRefuseEnterDuplItems, deleteDupl }
